You are currently looking at version 1.0 of this notebook. To download notebooks and datafiles, as well as get help on Jupyter notebooks in the Coursera platform, visit the Jupyter Notebook FAQ course resource.


Assignment 4 - Understanding and Predicting Property Maintenance Fines

This assignment is based on a data challenge from the Michigan Data Science Team (MDST).

The Michigan Data Science Team (MDST) and the Michigan Student Symposium for Interdisciplinary Statistical Sciences (MSSISS) have partnered with the City of Detroit to help solve one of the most pressing problems facing Detroit - blight. Blight violations are issued by the city to individuals who allow their properties to remain in a deteriorated condition. Every year, the city of Detroit issues millions of dollars in fines to residents and every year, many of these fines remain unpaid. Enforcing unpaid blight fines is a costly and tedious process, so the city wants to know: how can we increase blight ticket compliance?

The first step in answering this question is understanding when and why a resident might fail to comply with a blight ticket. This is where predictive modeling comes in. For this assignment, your task is to predict whether a given blight ticket will be paid on time.

All data for this assignment has been provided to us through the Detroit Open Data Portal. Only the data already included in your Coursera directory can be used for training the model for this assignment. Nonetheless, we encourage you to look into data from other Detroit datasets to help inform feature creation and model selection. We recommend taking a look at the following related datasets:


We provide you with two data files for use in training and validating your models: train.csv and test.csv. Each row in these two files corresponds to a single blight ticket, and includes information about when, why, and to whom each ticket was issued. The target variable is compliance, which is True if the ticket was paid early, on time, or within one month of the hearing data, False if the ticket was paid after the hearing date or not at all, and Null if the violator was found not responsible. Compliance, as well as a handful of other variables that will not be available at test-time, are only included in train.csv.

Note: All tickets where the violators were found not responsible are not considered during evaluation. They are included in the training set as an additional source of data for visualization, and to enable unsupervised and semi-supervised approaches. However, they are not included in the test set.


File descriptions (Use only this data for training your model!)

train.csv - the training set (all tickets issued 2004-2011)
test.csv - the test set (all tickets issued 2012-2016)
addresses.csv & latlons.csv - mapping from ticket id to addresses, and from addresses to lat/lon coordinates. 
 Note: misspelled addresses may be incorrectly geolocated.


Data fields

train.csv & test.csv

ticket_id - unique identifier for tickets
agency_name - Agency that issued the ticket
inspector_name - Name of inspector that issued the ticket
violator_name - Name of the person/organization that the ticket was issued to
violation_street_number, violation_street_name, violation_zip_code - Address where the violation occurred
mailing_address_str_number, mailing_address_str_name, city, state, zip_code, non_us_str_code, country - Mailing address of the violator
ticket_issued_date - Date and time the ticket was issued
hearing_date - Date and time the violator's hearing was scheduled
violation_code, violation_description - Type of violation
disposition - Judgment and judgement type
fine_amount - Violation fine amount, excluding fees
admin_fee - $20 fee assigned to responsible judgments

state_fee - $10 fee assigned to responsible judgments late_fee - 10% fee assigned to responsible judgments discount_amount - discount applied, if any clean_up_cost - DPW clean-up or graffiti removal cost judgment_amount - Sum of all fines and fees grafitti_status - Flag for graffiti violations

train.csv only

payment_amount - Amount paid, if any
payment_date - Date payment was made, if it was received
payment_status - Current payment status as of Feb 1 2017
balance_due - Fines and fees still owed
collection_status - Flag for payments in collections
compliance [target variable for prediction] 
 Null = Not responsible
 0 = Responsible, non-compliant
 1 = Responsible, compliant
compliance_detail - More information on why each ticket was marked compliant or non-compliant



Evaluation

Your predictions will be given as the probability that the corresponding blight ticket will be paid on time.

The evaluation metric for this assignment is the Area Under the ROC Curve (AUC).

Your grade will be based on the AUC score computed for your classifier. A model which with an AUROC of 0.7 passes this assignment, over 0.75 will recieve full points.


For this assignment, create a function that trains a model to predict blight ticket compliance in Detroit using train.csv. Using this model, return a series of length 61001 with the data being the probability that each corresponding ticket from test.csv will be paid, and the index being the ticket_id.

Example:

ticket_id
   284932    0.531842
   285362    0.401958
   285361    0.105928
   285338    0.018572
             ...
   376499    0.208567
   376500    0.818759
   369851    0.018528
   Name: compliance, dtype: float32

In [3]:
import pandas as pd
import numpy as np

def blight_model():
    
    from sklearn.model_selection import train_test_split
    from sklearn.neural_network import MLPClassifier
    from sklearn.preprocessing import MinMaxScaler

    df_train = pd.read_csv('train.csv', encoding = "ISO-8859-1")
    df_test = pd.read_csv('test.csv', encoding = "ISO-8859-1")


    list_to_remove = ['balance_due',
     'collection_status',
     'compliance_detail',
     'payment_amount',
     'payment_date',
     'payment_status']

    list_to_remove_all = ['violator_name', 'zip_code', 'country', 'city',
                          'inspector_name', 'violation_street_number', 'violation_street_name',
                          'violation_zip_code', 'violation_description',
                          'mailing_address_str_number', 'mailing_address_str_name',
                          'non_us_str_code',
                          'ticket_issued_date', 'hearing_date', 'admin_fee']

    df_train.drop(list_to_remove, axis=1, inplace=True)
    df_train.drop(list_to_remove_all, axis=1, inplace=True)
    df_test.drop(list_to_remove_all, axis=1, inplace=True)

    df_train.drop('grafitti_status', axis=1, inplace=True)
    df_test.drop('grafitti_status', axis=1, inplace=True)

    ###
    df_latlons = pd.read_csv('latlons.csv')
    df_address =  pd.read_csv('addresses.csv')
    df_id_latlons = df_address.set_index('address').join(df_latlons.set_index('address'))

    df_train = df_train.set_index('ticket_id').join(df_id_latlons.set_index('ticket_id'))
    df_test = df_test.set_index('ticket_id').join(df_id_latlons.set_index('ticket_id'))

    ###
    vio_code_freq10 = df_train.violation_code.value_counts().index[0:10]
    df_train['violation_code_freq10'] = [list(vio_code_freq10).index(c) if c in vio_code_freq10 else -1 for c in df_train.violation_code ]
    df_train.drop('violation_code', axis=1, inplace=True)
    df_test['violation_code_freq10'] = [list(vio_code_freq10).index(c) if c in vio_code_freq10 else -1 for c in df_test.violation_code ]
    df_test.drop('violation_code', axis=1, inplace=True)

    ###
    df_train = df_train[df_train.compliance.isnull() == False]

    df_train.lat.fillna(method='pad', inplace=True)
    df_train.lon.fillna(method='pad', inplace=True)
    df_train.state.fillna(method='pad', inplace=True)

    df_test.lat.fillna(method='pad', inplace=True)
    df_test.lon.fillna(method='pad', inplace=True)
    df_test.state.fillna(method='pad', inplace=True)

    one_hot_encode_columns = ['agency_name', 'state', 'disposition', 'violation_code_freq10']

    df_train = pd.get_dummies(df_train, columns=one_hot_encode_columns)
    df_test = pd.get_dummies(df_test, columns=one_hot_encode_columns)
        
    ## Resampling:
    df_train.sort_values('compliance', ascending=False, inplace=True)
    num_of_com = int(df_train.compliance.sum())
    df_train = df_train.append([df_train[0:num_of_com]]*10, ignore_index=True)
    ## End of Resampling

    train_features = df_train.columns.drop('compliance')

    #######
    X_train = df_train[train_features]
    y_train = df_train.compliance

    X_test = df_test
    l1 = list(set(X_test.columns) - set(X_train.columns))
    X_test.drop(l1, axis=1, inplace=True)

    l2 = list(set(X_train.columns) - set(X_test.columns))
    X_train = X_train.drop(l2, axis=1)

    #######

    scaler = MinMaxScaler()

    X_train_scaled = scaler.fit_transform(X_train)
    X_test_scaled = scaler.transform(X_test)

    clf = MLPClassifier(hidden_layer_sizes = [500, 50], alpha = 0.00,
                    random_state = 0,
                    shuffle = False,
                    learning_rate_init = 0.005,
                    batch_size = 1000,
                    learning_rate = 'invscaling',
                    momentum = 0.1,
                    power_t = 0.001,
                    verbose = False,
                    max_iter = 400,
                    tol = 0.0001,
                    solver='adam')
    clf.fit(X_train_scaled, y_train)

    test_proba = clf.predict_proba(X_test_scaled)[:,1]
    test_df = pd.read_csv('test.csv', encoding = "ISO-8859-1")
    test_df['compliance'] = test_proba
    test_df.set_index('ticket_id', inplace=True)
    
    return test_df.compliance

In [4]:
# blight_model()


/Users/fuyangliu/Workspace/coursera-Applied-Machine-Learning-in-Python/venv/lib/python3.6/site-packages/IPython/core/interactiveshell.py:2808: DtypeWarning: Columns (11,12,31) have mixed types. Specify dtype option on import or set low_memory=False.
  if self.run_code(code, result):
Out[4]:
ticket_id
284932    5.023249e-01
285362    1.150819e-01
285361    4.902488e-01
285338    3.596550e-01
285346    5.048895e-01
285345    3.601789e-01
285347    4.484137e-01
285342    9.862825e-01
285530    1.133933e-11
284989    2.482247e-01
285344    4.187701e-01
285343    1.270819e-01
285340    1.268472e-01
285341    4.188369e-01
285349    3.829482e-01
285348    3.689750e-01
284991    5.928852e-08
285532    1.803016e-01
285406    1.683003e-01
285001    2.146812e-01
285006    1.052421e-01
285405    1.723619e-01
285337    2.025021e-08
285496    4.059226e-01
285497    3.362007e-01
285378    1.747659e-01
285589    2.898269e-08
285585    3.104897e-01
285501    4.983714e-01
285581    1.153603e-01
              ...     
376367    1.272612e-01
376366    3.096337e-01
376362    7.170108e-01
376363    5.978917e-01
376365    1.272612e-01
376364    3.096337e-01
376228    3.796976e-01
376265    3.041103e-01
376286    8.223874e-01
376320    3.587434e-01
376314    3.646927e-01
376327    8.431212e-01
376385    8.436773e-01
376435    9.919017e-01
376370    9.984043e-01
376434    5.536513e-01
376459    4.740240e-01
376478    2.018654e-02
376473    3.611286e-01
376484    1.599667e-01
376482    1.081370e-02
376480    9.125954e-08
376479    9.125954e-08
376481    9.125954e-08
376483    1.647107e-05
376496    6.798440e-02
376497    6.798440e-02
376499    4.795230e-01
376500    4.795062e-01
369851    9.180494e-01
Name: compliance, Length: 61001, dtype: float64

In [ ]: